(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
		typeof define === 'function' && define.amd ? define(['exports'], factory) :
			(factory((global.wecharts = {})));
}(this, (function (exports) {
	'use strict';

	var canvas;
	var ctx = null;

	const HEIGHT = 600;

	const WIDTH = 600;

	const OffsetLeft = 50;
	const OffsetTop = 50;

	const ArrowWidth = 6;
	const ArrowHeight = 10;

	var defaultOption = {

		title: '图表案例',

		yAxisSectionSize: 0, // 数据分段的区间范围大小

		yAxisSectionHeight: 50, // y轴默认每一段的高度

		yAxisHrLineColor: '#b2ebf2', // y轴横线的颜色

		xAxis: {
			name: '横轴',
			boundaryGap: false,
			data: []
		},

		lineColor: '#5d4037'
	}

	// 折线点的事件集合
	var rectEvent = [];

	function init(dom) {
		console.log('init canvas');
		canvas = document.createElement('canvas');
		canvas.width = Number.parseInt(dom.getAttribute('width'));
		canvas.height = Number.parseInt(dom.getAttribute('height'));
		dom.appendChild(canvas);
		ctx = canvas.getContext('2d');
	}

	/**
	 * 设置属性
	 * @param data
	 */
	function setOptions(data) {
		defaultOption.xAxis.name = data.xAxis.name;
		defaultOption.xAxis.data = data.xAxis.data;
		defaultOption.xAxis.boundaryGap = data.xAxis.boundaryGap;
		defaultOption.title = data.title ? data.title : defaultOption.title;
		drawTitle();
		drawAxis(data);
		drawLines(data);
	}

	/**
	 * 画标题
	 */
	function drawTitle() {
		ctx.font = '40px sans-serif';
		ctx.fillText(defaultOption.title, WIDTH / 2, OffsetTop, 100);
		ctx.font = '16px sans-serif';
	}

	/**
	 * 画坐标轴
	 */
	function drawAxis(data) {
		let xAxis = data.xAxis
		let yAxis = data.yAxis

		// 画横轴 -------------------------------
		ctx.beginPath();
		ctx.moveTo(OffsetLeft, HEIGHT);
		ctx.lineTo(WIDTH, HEIGHT);
		ctx.closePath();
		ctx.stroke();
		// 横轴箭头
		ctx.beginPath();
		ctx.moveTo(WIDTH, HEIGHT);
		ctx.lineTo(WIDTH, HEIGHT - ArrowWidth);
		ctx.lineTo(WIDTH + ArrowHeight, HEIGHT);
		ctx.lineTo(WIDTH, HEIGHT + ArrowWidth);
		ctx.lineTo(WIDTH, HEIGHT);
		ctx.closePath();
		ctx.fill();
		ctx.fillText(xAxis.name, WIDTH + ArrowHeight + 10, HEIGHT); // 横轴名称

		// 画横轴坐标分组点
		let xSectionWidth = (WIDTH - OffsetLeft - 50) / defaultOption.xAxis.data.length;
		for (let k = 0; k < defaultOption.xAxis.data.length; k++) {
			ctx.beginPath();
			ctx.moveTo(OffsetLeft + (k + 1) * xSectionWidth, HEIGHT);
			ctx.lineTo(OffsetLeft + (k + 1) * xSectionWidth, HEIGHT - 5);
			ctx.closePath();
			ctx.stroke();
			ctx.fillText(defaultOption.xAxis.data[k], OffsetLeft + (k + 1) * xSectionWidth - 10, HEIGHT + 20, 30);
		}

		// 画纵轴 ---------------------------------
		ctx.beginPath();
		ctx.moveTo(OffsetLeft, HEIGHT);
		ctx.lineTo(OffsetLeft, OffsetTop);
		ctx.closePath();
		ctx.stroke();
		// 纵轴箭头
		ctx.beginPath();
		ctx.moveTo(OffsetLeft, OffsetTop);
		ctx.lineTo(OffsetLeft - ArrowWidth, OffsetTop);
		ctx.lineTo(OffsetLeft, OffsetTop - ArrowHeight);
		ctx.lineTo(OffsetLeft + ArrowWidth, OffsetTop);
		ctx.lineTo(OffsetLeft, OffsetTop);
		ctx.closePath();
		ctx.fill();
		ctx.fillText(yAxis.name, 20, OffsetTop - ArrowHeight, 100); // 纵轴名称

		let stdDev = 0; // 标准差四舍五入之后的整数，也用于纵轴每个分组的间隔
		let maxNumber = 0; // 所有数据的最大值
		data.series.forEach(serie => {
			let tempSerieData = JSON.parse(JSON.stringify(serie.data))
			tempSerieData.sort((a, b) => {
				return b - a;
			});
			if (tempSerieData[0] > maxNumber) {
				maxNumber = tempSerieData[0]
			}
			let r = computeTotalStandardDeviation(serie.data);
			if (r > stdDev) {
				stdDev = r;
			}
		});
		console.log(stdDev)
		console.log(maxNumber)
		let sectionSize = round(stdDev); // 分组大小
		defaultOption.yAxisSectionSize = sectionSize
		console.log(sectionSize)
		let sectionCount = Math.ceil(maxNumber/sectionSize); // 纵轴分组数
		console.log(sectionCount)

		let sectionHeight = (HEIGHT - OffsetTop - 50) / sectionCount; // 每一段的高度
		defaultOption.yAxisSectionHeight = sectionHeight
		console.log(sectionHeight)
		// 画垂直纵轴的横向分段线
		ctx.fillText('0', 20, HEIGHT, 20);
		for (let i = 0; i < sectionCount; i++) {
			ctx.beginPath();
			ctx.moveTo(OffsetLeft, HEIGHT - (i + 1) * sectionHeight);
			ctx.lineTo(WIDTH, HEIGHT - (i + 1) * sectionHeight);
			ctx.closePath();
			ctx.strokeStyle = defaultOption.yAxisHrLineColor;
			ctx.stroke();
			ctx.fillText((i + 1) * sectionSize + '', 20, HEIGHT - (i + 1) * sectionHeight, 20);
		}
	}

	/**
	 * 画折线
	 * @param data
	 */
	function drawLines(data) {
		data.series.forEach(serie => {
			if (serie.type === 'line') {
				drawLine(serie.data)
			}
		});
	}


	/**
	 * 画一条折线
	 * @param data
	 */
	function drawLine(data) {
		console.log(data);
		if (defaultOption.xAxis.data.length <= 0) {
			console.error('横轴未配置');
		}
		let xSectionWidth = (WIDTH - OffsetLeft - 50) / defaultOption.xAxis.data.length; // 横轴每一段宽度
		let onePerHeight = defaultOption.yAxisSectionHeight / defaultOption.yAxisSectionSize; // 单位数值下height值
		for (let j = 0; j < data.length; j++) {
			let currentValueHeight = HEIGHT - data[j] * onePerHeight; // 当前数的高度
			let currentValueWidth = 50 + (j + 1) * xSectionWidth; // 当前数值所在的宽即距左边距离
			ctx.fillRect(currentValueWidth - 5, currentValueHeight - 5, 10, 10);
			ctx.fill();
			const count = j + 1;
			rectEvent.push({
				rx: currentValueWidth - 5,
				ry: currentValueHeight - 5,
				event: function () {
					console.log('点击了第' + count + '个点');
					alert('点击了第' + count + '个点');
				}
			});
		}
		let linePathObj = new Path2D();
		linePathObj.moveTo(50 + (0 + 1) * xSectionWidth, HEIGHT - data[0] * onePerHeight);
		for (let j = 0; j < data.length; j++) {
			linePathObj.lineTo(50 + (j + 1) * xSectionWidth, HEIGHT - data[j] * onePerHeight);
			linePathObj.moveTo(50 + (j + 1) * xSectionWidth, HEIGHT - data[j] * onePerHeight);
		}
		ctx.strokeStyle = defaultOption.lineColor;
		ctx.stroke(linePathObj);

		canvas.addEventListener('click', function (event) {
			checkPointIsRect(event.offsetX, event.offsetY);
		});
	}


	function checkPointIsRect(x, y) {
		console.log(x);
		console.log(y);
		rectEvent.forEach(re => {
			if (x <= re.rx + 10 && x >= re.rx && y <= re.ry + 10 && y >= re.ry) {
				let fn = re.event;
				fn();
			}
		});
	}

	/**
	 * 计算标准差
	 * @param data
	 */
	function computeStandardDeviation(data) {
		let sum = function(x,y){ return x+y;};　　//求和函数
		let square = function(x){ return x*x;};　　//数组中每个元素求它的平方

		let mean = data.reduce(sum)/data.length; // 平均值
		let deviations = data.map(function(x){return x-mean;}); // 偏差
		let stdDev = Math.sqrt(deviations.map(square).reduce(sum)/(data.length-1)); // 标准差
		console.log("标准差："+stdDev);
		return stdDev;
	}

	/**
	 * 计算总体标准差
	 * @param data
	 */
	function computeTotalStandardDeviation(data) {
		let sum = function(x,y){ return x+y;};　　//求和函数
		let square = function(x){ return x*x;};　　//数组中每个元素求它的平方

		let mean = data.reduce(sum)/data.length; // 平均值
		let deviations = data.map(function(x){return x-mean;}); // 偏差
		let stdDev = Math.sqrt(deviations.map(square).reduce(sum)/(data.length)); // 总体标准差
		console.log("总体标准差："+stdDev);
		return stdDev;
	}

	/**
	 * 小数向上取整
	 * @param floatNumber
	 * @returns {number}
	 */
	function ceil(floatNumber) {
		return Math.ceil(floatNumber)
	}

	/**
	 * 四舍五入取离最近的整数, 比如49.1 取50
	 * @param floatNumber
	 * @returns {number}
	 */
	function round(floatNumber) {
		let fr = Math.round(floatNumber);
		let ns = fr + '';
		let nc = ns.length;
		if (nc >= 2) {
			let tr = Math.round(fr / Math.pow(10, nc - 1)) * Math.pow(10, nc - 1);
			return tr;
		} else {
			return fr
		}
	}


	exports.init = init;
	exports.setOptions = setOptions;
	exports.computeStandardDeviation = computeStandardDeviation
	exports.computeTotalStandardDeviation = computeTotalStandardDeviation
	exports.round = round
})));